package com.gwtsz.chart.output.customer;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.gwtsz.chart.charts.CombinedChart;
import com.gwtsz.chart.data.CandleDataSet;
import com.gwtsz.chart.data.CandleEntry;
import com.gwtsz.chart.data.CombinedData;
import com.gwtsz.chart.data.Entry;
import com.gwtsz.chart.highlight.Highlight;
import com.gwtsz.chart.interfaces.datasets.ILineScatterCandleRadarDataSet;
import com.gwtsz.chart.listener.OnChartDataListenner;
import com.gwtsz.chart.listener.onChartStateListenner;
import com.gwtsz.chart.output.bean.DataParse;
import com.gwtsz.chart.output.bean.KLineBean;
import com.gwtsz.chart.output.utils.ChartThemeUtil;
import com.gwtsz.chart.output.utils.GTTKDataModel;
import com.gwtsz.chart.utils.Transformer;

import java.text.DecimalFormat;

/**
 * Created by spence on 2017/2/27.
 */

public class MyCombinedChart extends CombinedChart{

    private MyRightMarkerView myMarkerViewRight;
    private MyRightMarkerView myNowPriceMarkerView;
    private MyBottomMarkerView mMyBottomMarkerView;
    private DataParse minuteHelper;
    private Context mContext;
    private CombinedData mCombinedData;
    private OnChartDataListenner mOnChartDataListenner;
    private onChartStateListenner mOnChartStateListenner;
    private boolean showCursor=false;
    private int nowIndex=getLowestVisibleXIndex();
    private boolean showNowPrice=false;
    private boolean refrashNew=false;
    private int lastMin=0;
    boolean nowPrice=false;


    public MyCombinedChart(Context context) {
        super(context);
    }

    public MyCombinedChart(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext=context;
    }

    public MyCombinedChart(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void init() {
        super.init();
    }


    public void setMarker(MyRightMarkerView markerRight,MyBottomMarkerView markerBottom, DataParse minuteHelper) {
        this.myMarkerViewRight = markerRight;
        this.mMyBottomMarkerView=markerBottom;
        this.minuteHelper = minuteHelper;

        myMarkerViewRight.setTextColor(0, ChartThemeUtil.instance().color_chart_cursor);
        mMyBottomMarkerView.setTextColor(0, ChartThemeUtil.instance().color_chart_cursor);
        myNowPriceMarkerView.setTextColor(0, ChartThemeUtil.instance().color_chart_price);
    }

    public void setMarker(MyRightMarkerView markerRight,MyBottomMarkerView markerBottom,MyRightMarkerView myNowPriceMarkerView) {
        this.myMarkerViewRight = markerRight;
        this.myNowPriceMarkerView=myNowPriceMarkerView;
        this.mMyBottomMarkerView=markerBottom;

        myMarkerViewRight.setTextColor(0, ChartThemeUtil.instance().color_chart_cursor);
        mMyBottomMarkerView.setTextColor(0, ChartThemeUtil.instance().color_chart_cursor);
        myNowPriceMarkerView.setTextColor(0, ChartThemeUtil.instance().color_chart_price);
    }


    public void setMarker(MyRightMarkerView markerRight,MyBottomMarkerView markerBottom,MyRightMarkerView myNowPriceMarkerView, CombinedData combinedData) {
        this.myMarkerViewRight = markerRight;
        this.myNowPriceMarkerView=myNowPriceMarkerView;
        this.mMyBottomMarkerView=markerBottom;
        this.mCombinedData = combinedData;
        lastMin=0;

        myMarkerViewRight.setTextColor(0, ChartThemeUtil.instance().color_chart_cursor);
        mMyBottomMarkerView.setTextColor(0, ChartThemeUtil.instance().color_chart_cursor);
        myNowPriceMarkerView.setTextColor(0, ChartThemeUtil.instance().color_chart_price);
    }
    public void setMarker(MyRightMarkerView markerRight,MyBottomMarkerView markerBottom,MyRightMarkerView myNowPriceMarkerView, CombinedData combinedData,DataParse minuteHelper) {
        setMarker(markerRight,markerBottom,myNowPriceMarkerView,combinedData);
        this.minuteHelper = minuteHelper;
    }

    @Override
    protected void drawMarkers(Canvas canvas) {
        //boolean nowPrice= getNowPrice();
        if(0==getData().getXValCount())return;
        int count=getXValCount();
        int numberMin=getRendererXAxis().getmMinX();
        int lookMin=getLowestVisibleXIndex();
        int lookMax=getRendererXAxis().getmMaxX();

        int time=minuteHelper.getkModel().get(getHighestVisibleXIndex()).priceTime;
        int viewNumber=getHighestVisibleXIndex()-getLowestVisibleXIndex();
        if(lastMin!=lookMin&&null!=mOnChartStateListenner) {
            mOnChartStateListenner.onRespon(time, viewNumber);
        }
        if(lastMin>lookMin&&lookMin==0){
            refrashNew=true;
        }
        if(count!=0&&null!=mOnChartDataListenner&&refrashNew){
            refrashNew=false;
            mOnChartDataListenner.updata(0);
        }

        if(null!=mOnChartStateListenner){
            String start=mData.getLineData().getXVals().get(lookMin);
            String end=mData.getLineData().getXVals().get(getHighestVisibleXIndex());
            mOnChartStateListenner.onResultData(start,end);
        }

        onShowRightArrow();

        if(null!=mOnChartStateListenner&&lastMin!=lookMin){
            onUpdateIndictor(count+1);
        }
        lastMin=lookMin;
        /** 区分主副图 主图=false **/
        if(nowPrice&&showNowPrice&&isMain()) {
                drawNowPrice(canvas);
        }
        if (!mDrawMarkerViews || !valuesToHighlight()) {
            if(null!=mOnChartStateListenner){
                if(showCursor) {
                    onHideCursor();
                    showCursor = false;
                }
            }

                return;
        }
        for (int i = 0; i < mIndicesToHighlight.length; i++) {
            Highlight highlight = mIndicesToHighlight[i];
            int xIndex = mIndicesToHighlight[i].getXIndex();
            if(xIndex<lookMin&&null!=mOnChartStateListenner&&highlight.getValue()!=Float.MAX_VALUE){
                Highlight highlights=new Highlight(lookMin,Float.MAX_VALUE,highlight.getDataIndex(),highlight.getDataSetIndex());
                mOnChartStateListenner.onHighlightValue(new Highlight[]{highlights});
                highlights=new Highlight(lookMin,highlight.getValue(),highlight.getDataIndex(),highlight.getDataSetIndex());
                highlightValues(new Highlight[]{highlights});
                return;
            }
            if(null!=mOnChartStateListenner) {
                showCursor=true;
                onShowCursor(true);
                onUpdateIndictor(xIndex);
                onDrawCursor(xIndex);
            }
            int dataSetIndex = mIndicesToHighlight[i].getDataSetIndex();
            float deltaX = mXAxis != null
                    ? mXAxis.mAxisRange
                    : ((mData == null ? 0.f : mData.getXValCount()) - 1.f);
            if (xIndex <= deltaX && xIndex <= deltaX * mAnimator.getPhaseX()) {
                //Entry e = mData.getEntryForHighlight(mIndicesToHighlight[i]);
                Entry e=new Entry(mIndicesToHighlight[i].getValue(),xIndex);
                // make sure entry not null
                if (e == null || e.getXIndex() != xIndex)
                    continue;

                float[] pos = getMarkerPosition(e, highlight);

                // check bounds
                if(!mViewPortHandler.isInBoundsLeft(pos[0])){
                    pos[0]=mViewPortHandler.getContentRect().left;
                }
                if(!mViewPortHandler.isInBoundsRight(pos[0])){
                    pos[0]=mViewPortHandler.getContentRect().right;
                }

                //float yValForXIndex2 = minuteHelper.getDatas().get(mIndicesToHighlight[i].getXIndex()).per;
                //String time = minuteHelper.getDatas().get(mIndicesToHighlight[i].getXIndex()).time;
                myMarkerViewRight.setData(mIndicesToHighlight[i].getValue());
                if(null!=mData.getLineData()) {
                    mMyBottomMarkerView.setData(mData.getLineData().getXVals().get(mIndicesToHighlight[i].getXIndex()));
                }else {
                    //微盘
                    mMyBottomMarkerView.setData(mData.getCandleData().getXVals().get(mIndicesToHighlight[i].getXIndex()));
                }
                myMarkerViewRight.refreshContent(e, mIndicesToHighlight[i]);
                mMyBottomMarkerView.refreshContent(e, mIndicesToHighlight[i]);

                /*修复bug*/
                // invalidate();
                /*重新计算大小*/
                myMarkerViewRight.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                myMarkerViewRight.layout(0, 0, myMarkerViewRight.getMeasuredWidth(),
                        myMarkerViewRight.getMeasuredHeight());
                mMyBottomMarkerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                mMyBottomMarkerView.layout(0, 0, mMyBottomMarkerView.getMeasuredWidth(),
                        mMyBottomMarkerView.getMeasuredHeight());

                if(getXAxis().isDrawLabelsEnabled()){
                    if(pos[0]<mMyBottomMarkerView.getWidth()/2){
                        mMyBottomMarkerView.draw(canvas, 0,
                            mViewPortHandler.contentBottom());
                    }else if(pos[0]+mMyBottomMarkerView.getWidth()/2>mViewPortHandler.contentRight()){
                        mMyBottomMarkerView.draw(canvas, mViewPortHandler.contentRight() - mMyBottomMarkerView.getWidth(),
                            mViewPortHandler.contentBottom());
                    }else {
                        mMyBottomMarkerView.draw(canvas, pos[0] - mMyBottomMarkerView.getWidth() / 2,
                            mViewPortHandler.contentBottom());
                    }
                }
                if(pos[1]<myMarkerViewRight.getHeight() / 2&&pos[1]>=0){
                    myMarkerViewRight.draw(canvas, mViewPortHandler.contentRight(),
                        0);
                }else {
                    myMarkerViewRight.draw(canvas, mViewPortHandler.contentRight(),
                        pos[1] - myMarkerViewRight.getHeight() / 2);
                }


            }
        }
    }


    private ILineScatterCandleRadarDataSet getSetData(){
        ILineScatterCandleRadarDataSet setData=null;
        if(null!=mCombinedData.getCandleData()){
            setData=mCombinedData.getCandleData().getDataSetByIndex(0);
        }else if(null!=mCombinedData.getStickData()){
            setData=mCombinedData.getCandleData().getDataSetByIndex(0);
        }else {
            int lastIndex = getLineData().getDataSetCount();
            setData = mCombinedData.getCandleData().getDataSetByIndex(lastIndex);
        }

        return setData;
    }

    /**
     * 画现价线
     * @param canvas
     */
    protected void drawNowPrice(Canvas canvas){

        int xIndex=mData.getDataSetByLabel("KLine",true).getEntryCount()-1;
        float valY=0;
        if(mData.getDataSetByLabel("KLine",true)instanceof CandleDataSet){
            valY=((CandleEntry)mData.getDataSetByLabel("KLine",true).getEntryForIndex(xIndex)).getClose();
        }else {
            valY=mData.getDataSetByLabel("KLine",true).getEntryForIndex(xIndex).getVal();
        }

        Transformer trans = getTransformer(mData.getDataSetByLabel("KLine",true).getAxisDependency());

        float[] pts = new float[2];
        pts[1] = valY;
        trans.pointValuesToPixel(pts);
        float moveY=pts[1];

        myNowPriceMarkerView.setData(valY);
        Entry e=new Entry(valY,mData.getXValCount()-1);
        myNowPriceMarkerView.refreshContent(e, null);
        myNowPriceMarkerView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        myNowPriceMarkerView.layout(0, 0, myNowPriceMarkerView.getMeasuredWidth(),
                myNowPriceMarkerView.getMeasuredHeight());

        if(moveY<myNowPriceMarkerView.getHeight() / 2&&moveY>=0){
            myNowPriceMarkerView.draw(canvas, mViewPortHandler.contentRight(),
                0);
        }else {
            myNowPriceMarkerView.draw(canvas, mViewPortHandler.contentRight(),
                moveY - myNowPriceMarkerView.getHeight() / 2);
        }

        Paint paint=mRenderer.getPaintHighlight();
        paint.setColor(ChartThemeUtil.instance().color_chart_price);
        //canvas.drawLine(mViewPortHandler.contentLeft(),moveY,mViewPortHandler.contentRight(),moveY,paint);
        //设置画虚线，如果之后不再使用虚线，调用paint.setPathEffect(null);
        PathEffect effects = new DashPathEffect(new float[]{15,15,15,15},1);
        paint.setPathEffect(effects);
        Path path = new Path();
        path.moveTo(mViewPortHandler.contentLeft(), moveY);
        path.lineTo(mViewPortHandler.contentRight(), moveY);
        canvas.drawPath(path,paint);

    }

    public void setListener(OnChartDataListenner onChartDataListenner){

        mOnChartDataListenner=onChartDataListenner;

    }

    public void setOnChartStateListenner(onChartStateListenner onChartStateListenner){
        mOnChartStateListenner=onChartStateListenner;
        mOnChartDataListenner=onChartStateListenner;
    }

    private void onShowRightArrow(){
        int count=getXValCount();
        //int lookMax=getRendererXAxis().getmMaxX();
        int lookMax=getHighestVisibleXIndex();
        if(lookMax<count-1&&null!=mOnChartStateListenner){
            mOnChartStateListenner.onShowRightArrow(true);
            nowPrice=false;
        }else if(lookMax==count-1&&null!=mOnChartStateListenner){
            mOnChartStateListenner.onShowRightArrow(false);
            nowPrice=true;
        }
    }
    @NonNull
    public void moveLastIndex(){
        moveViewToX(getXValCount() - 1);
    }
    @NonNull
    public void onUpdateIndictor(int curOffset){
        mOnChartStateListenner.onUpdateIndictor(curOffset);
        Log.e("curoffset",""+curOffset);
    }
    @NonNull
    private void onShowCursor(boolean enabled){
        mOnChartStateListenner.onShowCursor(enabled);
    }
    @NonNull
    private void onHideCursor(){
        mOnChartStateListenner.onHideCursor();
    }
    @NonNull
    private void onDrawCursor(int index){
        if(null==minuteHelper||minuteHelper.getkModel().size()<=index)return;
        double closePrice=0;
        if(index==0){
            closePrice=minuteHelper.getkModel().get(index).lastPrice;
        }else {
            closePrice=minuteHelper.getkModel().get(index-1).lastPrice;
        }
        GTTKDataModel dataModel=minuteHelper.getkModel().get(index);
        mOnChartStateListenner.onDrawCursor(closePrice,dataModel);
    }
    public void showXAxis(boolean swich){
        getXAxis().setDrawLabels(swich);
        invalidate();
    }

    public void onNextIndictor(){
        if(null!=mOnChartStateListenner)
        mOnChartStateListenner.onNextIndictor();
    }

    public void showNowPrice(boolean select){
        showNowPrice=select;
    }

    public boolean getNowPrice(){
        return nowPrice;
    }

    public void refreshProductDecimalNum(DecimalFormat decimalFormat){
        myMarkerViewRight.setmFormat(decimalFormat);
        myNowPriceMarkerView.setmFormat(decimalFormat);
    }

    public void noDataView(){
        /*getAxisRight().setAxisMaxValue(0f);*/
        getAxisRight().setAxisMinValue(0f);
        CombinedData combinedData=new CombinedData();
        setData(combinedData);
        notifyDataSetChanged();
        invalidate();
    }

    public void addEntryToMinuteHelper(KLineBean kLineBean){
        GTTKDataModel gttkDataModel=new GTTKDataModel(Integer.parseInt(kLineBean.date),kLineBean.open,kLineBean.high,kLineBean.low,kLineBean.close,kLineBean.changePrice,kLineBean.range,0);
        minuteHelper.getkModel().add(gttkDataModel);
    }

    public void refrashEntryToMinuteHelper(KLineBean kLineBean){
        GTTKDataModel gttkDataModel=new GTTKDataModel(Integer.parseInt(kLineBean.date),kLineBean.open,kLineBean.high,kLineBean.low,kLineBean.close,kLineBean.changePrice,kLineBean.range,0);
        minuteHelper.getkModel().set(minuteHelper.getkModel().size()-1,gttkDataModel);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(null!=mOnChartStateListenner)
            mOnChartStateListenner.onTouch(event);
        return super.onTouchEvent(event);
    }
}
